﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Engine.Base;
using log4net;

namespace Engine.Rendering
{
    public class RenderingSystem : ISubSystem
    {
        #region Methods
        public void Draw(GameTime gameTime, IRenderCamera camera, IEnumerable<IDrawable> drawables)
        {
            foreach (var d in drawables)
                Draw(gameTime, camera, d);
        }

        public void Draw(GameTime gameTime, IRenderCamera camera, IDrawable drawable)
        {
            drawable.Draw(gameTime, camera);
        }

        public BasicEffect ComputeEffect(BasicEffect e, IRenderCamera camera, IDrawable drawable, Matrix transform)
        {
            e.World = transform * Engine.Base.Helper.RenderHelper.CreateWorld(drawable.Position, drawable.Rotation);
            e.Projection = camera.Projection;
            e.View = camera.View;
            return e;
        }



        public void DrawModel(Model m, IRenderCamera camera, IDrawable drawable)
        {
            Matrix[] transforms = new Matrix[m.Bones.Count];
            m.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in m.Meshes)
            {
                foreach (BasicEffect e in mesh.Effects)
                {
                    e.World = transforms[mesh.ParentBone.Index] * Engine.Base.Helper.RenderHelper.CreateWorld(drawable.Position, drawable.Rotation);
                    e.Projection = camera.Projection;
                    e.View = camera.View;                    
                }
                mesh.Draw();
            }
        }
        #endregion // Methods


        #region ISubSystem-Implementation
        public void Start()
        {
            Logger.Debug("Starting RenderingSystem");
        }

        public void Stop()
        {
            Logger.Debug("Stoping RenderingSystem");
        }
        #endregion // ISubSystem-Implementation



        
        #region STATIC
        private static ILog Logger { get; set; }
        static RenderingSystem()
        {
            Logger = LogManager.GetLogger(typeof(RenderingSystem));
        }
        #endregion // STATIC
    }
}
